﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;

public class HeroController : MonoBehaviour {

    public MainUI mainUI;
    public float maxSpeed = 10;
    Rigidbody2D rigibody2d;
    public GameObject gun;
    public Transform gunFirePos;
    public GameObject buttle;
    public CheckEnemy checkEnemy;

	// Use this for initialization
	void Start () {
        rigibody2d = GetComponent<Rigidbody2D>();

    }
	
	// Update is called once per frame
	void Update () {
        float h = CrossPlatformInputManager.GetAxis("Horizontal");
        float v = CrossPlatformInputManager.GetAxis("Vertical");
        HeroMove(h, v);
        if (Input.GetKeyDown(KeyCode.Space))
            OpenFire();

        GunDir();
    }

    public void OpenFire()
    {
            GameObject go = Instantiate(buttle);
            go.transform.position = gunFirePos.position;
            go.transform.rotation = gunFirePos.rotation;
        //Vector2 dir = MonoUtils.Vector3ToVector2(gunFirePos.position - transform.position);
        //print("后坐力" + dir);
        //GetComponent<Rigidbody2D>().AddForce(Vector2.left * 10, ForceMode2D.Impulse);
    }

    void HeroMove(float h, float v)
    {
        //rigibody2d.velocity = new Vector2(h * maxSpeed, v * maxSpeed);
        rigibody2d.velocity = mainUI.moveValue * maxSpeed;
        gun.transform.up = new Vector3(mainUI.moveValue.x, mainUI.moveValue.y, 0);
    }
    /// <summary>
    /// 开火
    /// </summary>
    void HeroFireGun()
    {
        if( Input.GetKeyDown(KeyCode.Space))
        {

        }
    }
	
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "Bullet")
        {
            print("被集中");
            Debug.Log(collision.offset);
            
            Vector2 dir = (transform.position - collision.transform.position).Vector3ToVector2();
            GetComponent<Rigidbody2D>().AddForce(dir * 10, ForceMode2D.Impulse);
        }

    }
	
    /// <summary>
    /// 枪口指向
    /// </summary>
    void GunDir()
    {
        if (checkEnemy.enemyList.Count > 0)
        {
            gun.transform.up = (checkEnemy.nearEnemy.transform.position - gun.transform.position).Vector3Up();
        }
    }

}

